package controllers

import java.io.File
import java.nio.file.Files

import config.{Global, MyFile}
import javax.inject.Inject
import org.apache.commons.io.FileUtils
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, Action, ControllerComponents, Headers}
import utils.Utils

import scala.concurrent.Await
import scala.concurrent.duration.Duration

class MotifController @Inject()(cc: ControllerComponents) extends AbstractController(cc) with MyFile {

  def motifPage = Action {
    Ok(views.html.motifs.motifPage())
  }

  def getMotifData = Action {
    Ok(Json.toJson(s"${Global.path}/Motif".listFile.map { dir =>
      val dirName = dir.getName
      val png = dir.listFiles.filter(_.getName.endsWith("png")).map(_.getName)
      Json.obj("dir" -> dirName, "png" -> png)
    }))
  }

  def getMotifImg(path: String) = Action { implicit request =>
    val file = s"${Global.path}/Motif/$path"
    SendImg(file.toFile, request.headers)
  }

  def SendImg(file: File, headers: Headers) = {
    val lastModifiedStr = file.lastModified().toString
    val MimeType = "image/jpg"
    val byteArray = Files.readAllBytes(file.toPath)
    val ifModifiedSinceStr = headers.get(IF_MODIFIED_SINCE)
    if (ifModifiedSinceStr.isDefined && ifModifiedSinceStr.get == lastModifiedStr) {
      NotModified
    } else {
      Ok(byteArray).as(MimeType).withHeaders(
        LAST_MODIFIED -> file.lastModified().toString
      )
    }
  }

  def openDreme(name: String) = Action { implicit request =>
    Ok(s"${Global.path}/Motif/$name/dreme.html".readFileToString).as(HTML)
  }

  def motifInfoPage(name:String,seq:String) = Action{
    Ok(views.html.motifs.motifInfoPage(name,seq))
  }

  def getSeqTable(name: String, seq: String) = Action {
    val s = seq.split("_").last.split('.').head
    Ok(Json.toJson( s"${Global.path}/Motif/$name/${name}_motif_peak_info.txt".readLines.tail.map(_.split("\t")).filter(_.head == s).map{x=>
       Json.obj("Motif" -> x.head,"Gene" -> x(1),"Site" -> x(2))
     }))
  }

}
